import os
from fastapi import APIRouter, Security
from server.util import return_code, check_password, random_str, is_admin_user, en_password
from server.response import RespBody
from server.database import db_manager
from server.user_data import server_user_data
from .request.account_req import UserLogin, AddUser, DelecteUser

router = APIRouter(prefix='/user', tags=['用户中心'])


@router.post('/login', response_model=RespBody, summary='用户登录')
async def login(post: UserLogin):
    user_info = await db_manager.fetch_one("SELECT id,password FROM user WHERE username = :username AND status=1", {"username": post.username})
    if not user_info:
        return return_code(201, msg="用户或者密码错误")
    elif check_password(post.password, user_info["password"]):
        token = random_str()
        result = return_code(200, {"token": token})
        result["data"] = {"token": token}
        server_user_data.add_user(token, {"id": user_info["id"], "username": post.username})
        return result
    else:
        return return_code(207, msg="用户或者密码错误")


@router.post('/add', response_model=RespBody, summary='添加新用户',
             dependencies=[Security(is_admin_user, scopes=["allow"])])
async def add_account(post: AddUser):
    user_info = await db_manager.fetch_one("SELECT id,password FROM user WHERE username = :username AND status=1", {"username": post.username})
    if not user_info:
        post.password = en_password(post.password)
        new_user_id = await db_manager.insert("user", post.model_dump())
        print(new_user_id)
        return return_code(200)
    else:
        return return_code(401, msg="用户已经存在")


@router.post('/logout', response_model=RespBody, summary='用户登出')
async def logout(token: str = Security(is_admin_user, scopes=["allow"])):
    server_user_data.remove_user(token)
    return return_code(200)


@router.delete('/delete', response_model=RespBody, summary='禁用用户',
            dependencies=[Security(is_admin_user, scopes=["allow"])])
async def delete_user(post: DelecteUser):
    user_info = await db_manager.fetch_one("SELECT id FROM user WHERE id = :id AND status=1", {"id": post.user_id})
    if user_info:
        await db_manager.update("user", {"status": 0}, "id=?", (post.user_id,))
        return return_code(200)
    else:
        return return_code(401, msg="用户不存在")


@router.get('/all', response_model=RespBody, summary='获取用户列表',
            dependencies=[Security(is_admin_user, scopes=["allow"])])
async def get_all_user(page: int = 1):
    field = "id,username,email,status,created_at"
    lib_app = await db_manager.fetch_all(f"SELECT {field} FROM user WHERE id>0 ORDER BY id DESC LIMIT 30 OFFSET {(page - 1) * 30}")
    result = return_code(200)
    if lib_app:
        result["data"] = lib_app
    else:
        result["data"] = []
    return result
